package com.example.springcloud.account.service.impl;

import com.example.springcloud.account.mapper.AccountMapper;
import com.example.springcloud.account.service.AccountService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deduct(Long userId, BigDecimal money) {
        log.info("账户服务 AT 模式：开始扣减余额");
        log.info("全局事务 XID: {}", RootContext.getXID());
        log.info("用户ID: {}, 扣减金额: {}", userId, money);

        int result = accountMapper.deduct(userId, money);
        if (result == 0) {
            String errorMsg = String.format("余额不足：用户ID=%d, 需要扣减=%.2f", userId, money);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        log.info("余额扣减成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductXa(Long userId, BigDecimal money) {
        log.info("账户服务 XA 模式：开始扣减余额");
        log.info("全局事务 XID: {}", RootContext.getXID());
        log.info("用户ID: {}, 扣减金额: {}", userId, money);

        int result = accountMapper.deduct(userId, money);
        if (result == 0) {
            String errorMsg = String.format("余额不足：用户ID=%d, 需要扣减=%.2f", userId, money);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        log.info("余额扣减成功");
    }
}
